package com.boang.controller;

import com.alibaba.nacos.common.utils.StringUtils;
import com.boang.resp.Result;
import com.boang.resp.ResultCodeEnum;
import com.boang.service.AliyunSmsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

/*
  @author: 13813
  @date: 2024/9/4 15:30
*/
@RestController
@RequestMapping("/sms")
public class SmsController {

    @Autowired
    private AliyunSmsServiceImpl aliyunSmsService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping("/send/{phone}")
    public Result<String> send(@PathVariable("phone") String phone) throws Exception {
        int code = ThreadLocalRandom.current().nextInt(1000, 10000);
        //查询是否用此手机号在5分钟内发过短信，如果发过则返回提示，否则可以
        BoundValueOperations<String, String> valueOps = redisTemplate.boundValueOps("code:" + phone);
        String rCode = valueOps.get();
        //如果redis中没有此手机号的验证码
        if (StringUtils.isEmpty(rCode)) {
            //向对方手机号发送验证码
            Result<String> result = aliyunSmsService.sendSms(phone, code);
            //如果发送验证码成功
            if (result.getCode().equals(ResultCodeEnum.SUCCESS.getCode())) {
                //存储到Redis中
                valueOps.set(String.valueOf(code), 5, TimeUnit.MINUTES);
            }
        } else {
            return Result.failed("5分钟内不允许再次发送验证码");
        }
        return Result.ok();
    }
}
